Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Polymorphism in java

Polymorphism Intro

Polymorphism is a fundamental concept in Object-Oriented Programming (OOP) and is one of the four main principles of OOP, along with encapsulation, inheritance, and abstraction. The term “polymorphism” is derived from the Greek words “poly” meaning many, and “morph” meaning forms. Thus, polymorphism refers to the ability of an object to take on many forms. In Java, polymorphism is mainly divided into two types: Compile-time Polymorphism and Runtime Polymorphism. Compile-time Polymorphism Also known as static polymorphism, this type of polymorphism is achieved by function overloading. Function overloading occurs when there are multiple functions with the same name but different parameters. Here’s an example:
Compile-time Polymorphism example in java class Helper { static int Multiply (int a, int b) { return a * b; } static double Multiply (double a, double b) { return a * b; } } class Main { public static void main (String [] args) { System.out.println (Helper.Multiply (2, 4)); System.out.println (Helper.Multiply (5.5, 6.3)); } }

Output

8 34.65
In this example, the Multiply method is overloaded with two different parameter types. Runtime Polymorphism Also known as dynamic polymorphism, this type of polymorphism is achieved by method overriding. Method overriding occurs when a subclass provides a specific implementation of a method that is already provided by its parent class. Here’s an example:
Runtime Polymorphism basic example in java class Animal { public void animalSound() { System.out.println("The animal makes a sound"); } } class Pig extends Animal { public void animalSound() { System.out.println("The pig says: wee wee"); } } class Dog extends Animal { public void animalSound() { System.out.println("The dog says: bow wow"); } } class Main { public static void main(String[] args) { Animal myAnimal = new Animal(); Animal myPig = new Pig(); Animal myDog = new Dog(); myAnimal.animalSound(); myPig.animalSound(); myDog.animalSound(); } }

Output

The animal makes a sound The pig says: wee wee The dog says: bow wow
In this example, the animalSound method is overridden in both the Pig and Dog classes. Polymorphism allows us to perform a single action in different ways, thus enabling programmers to use objects of different types interchangeably. It is a powerful feature that enhances the flexibility and reusability of code.

  📌TAGS

★Class ★ Method ★ Object ★ java ★ oops ★ Polymorphism ★ method overloading ★ method overriding

Tutorials